package com.java.miaosha.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.miaosha.constants.Constants;
import com.java.miaosha.dao.UserDao;
import com.java.miaosha.entity.UserEntity;
import com.java.miaosha.exception.GlobalException;
import com.java.miaosha.service.UserService;
import com.java.miaosha.util.CookieUtils;
import com.java.miaosha.util.MD5Util;
import com.java.miaosha.util.RedisUtils;
import com.java.miaosha.util.Result;
import com.java.miaosha.vo.LoginVO;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
	@Autowired
	private UserDao userDao;
	@Autowired
	private RedisUtils redisUtils;

	@Override
	public Result login(LoginVO loginVO, HttpServletRequest request, HttpServletResponse response) {
   		UserEntity userEntity = userDao.selectById(loginVO.getMobile());
		if (userEntity == null) {
			throw new GlobalException(Constants.USER_NOT_EXISTS);
		}
		String s = MD5Util.MD5(loginVO.getPassword(), userEntity.getSalt());
		if (ObjectUtils.notEqual(s, userEntity.getPassword())) {
			throw new GlobalException(Constants.USERNAME_OR_PASSWORD_ERROR);
		}
		String token = UUID.randomUUID().toString().replace("-","");
		//生成uuid作为token的值保存在cookie中
		CookieUtils.setCookie(request,response,Constants.TOKEN,token,7200);
		//将用户保存在redis, key=token,value=user
		redisUtils.set(token, userEntity,7200L);
		return Result.ok();

	}

	@Override
	public UserEntity getUserByToken(String token) {
		if (token == null) {
			return null;
		}
		return redisUtils.get(token,UserEntity.class,7200L);
	}
}